package org.deng.vertx.web.controller;

import io.vertx.core.Vertx;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author: DengLibin
 * @Date: Create in 2022-05-08 17:05:49
 * @Description: 获取RequestBody
 */
@Slf4j
public class BodyController implements RouterController {

    public BodyController(Vertx vertx){

    }
    @Override
    public void configRouter(Router router) {
        log.info("配置BodyController");
        router.route("/body/test").method(HttpMethod.POST).handler(this::bodyTest);
        router.route("/body/upload").method(HttpMethod.POST).handler(this::upload);
        //第二种文件上传 (要关闭BodyHandler, 不然 BodyHandler会处理文件,这里再次处理报重复读取Request异常)
        router.post("/body/requestUpload").handler(this::requestUpload);
        
    }

    /**
     *获取body
     * @param ctx
     */
    private void bodyTest(RoutingContext ctx){
        String body = ctx.getBodyAsString();
        ctx.end(body);
    }

    
    /**
     *文件上传
     * @param ctx
     */
    private void upload(RoutingContext ctx){
       ctx.fileUploads().forEach(file->{
           log.info("文件上传,uploadedFileName:{}, fileName:{}, name:{}",
            file.uploadedFileName(), file.fileName(), file.name());
            
       });
       ctx.end("上传成功");
    }

    /**
     * 文件上传
     * @param ctx
     */
    private void requestUpload(RoutingContext ctx) {
        log.info("--------------------------------requestUpload------------------------------");
        HttpServerRequest request =  ctx.request();
        request.setExpectMultipart(true);
        request.uploadHandler(upload ->{
            upload.streamToFileSystem("requestUpload/"+upload.filename());
            if(request.isEnded()){
                ctx.end("上传成功");
            }
        });
    }

    
}
